<template>
<div>
  <!--  面包屑导航区-->
  <el-breadcrumb separator-class="el-icon-arrow-right">
    <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    <el-breadcrumb-item>用户列表</el-breadcrumb-item>
  </el-breadcrumb>
  <!--  卡片视图区-->
  <el-card>
<!--    搜索功能区-->
    <el-row :gutter="20">
      <el-col :span="8">
        <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
          <el-button slot="append" icon="el-icon-search" @click="getUserList"/>
        </el-input>
      </el-col>
      <el-col :span="3">
        <el-button type="primary" @click="addUser">添加用户</el-button>
      </el-col>
    </el-row>
<!--    表格区-->
    <el-table
      border
      stripe
      :data="userList"
      style="width: 100%">
      <el-table-column type="index" width="30"/>
      <el-table-column prop="username" label="用户名" width="180"/>
      <el-table-column prop="email" label="邮箱" width="180"/>
      <el-table-column prop="mobile" label="电话" width="180"/>
      <el-table-column prop="role_name" label="角色" width="180"/>
      <el-table-column prop="mg_state" label="状态" width="130">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)"/>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="editUser(scope.row.id)"/>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserBtn(scope.row.id)"/>
          <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
            <el-button type="warning" icon="el-icon-setting" size="mini"/>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
<!--    分页效果实现-->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page.sync="queryInfo.pagenum"
      :page-sizes="[1, 3, 5, 10]"
      :page-size="queryInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
  </el-card>
  <!--  添加用户对话框-->
  <el-dialog
    title="添加用户"
    :visible.sync="addUserdDialogVisible"
    @close="addUserClosed"
    width="50%">
    <!--  主体区域  -->
    <el-form class="login_form" :model="addUserForm" :rules="addUserFormRules" ref="addUserFormRef" >
      <el-form-item prop="username" label-width="70px" label="用户名">
        <el-input v-model="addUserForm.username"/>
      </el-form-item>
      <el-form-item prop="password" label-width="70px" label="密码">
        <el-input v-model="addUserForm.password"/>
      </el-form-item>
      <el-form-item prop="email" label-width="70px" label="邮箱">
        <el-input v-model="addUserForm.email"/>
      </el-form-item>
      <el-form-item prop="mobile" label-width="70px" label="手机">
        <el-input v-model="addUserForm.mobile"/>
      </el-form-item>
    </el-form>
    <!--    底部区域-->
    <span slot="footer" class="dialog-footer">
    <el-button @click="addUserdDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addUserBtn">确 定</el-button>
  </span>
  </el-dialog>
<!--  修改用户对话框-->
  <el-dialog
    title="修改用户"
    :visible.sync="editdDialogVisible"
    @close="editDialogClosed"
    width="50%">
    <!--    底部区域-->
    <el-form class="login_form" :model="editUserForm" :rules="editUserFormRules" ref="editUserFormRef" >
      <el-form-item prop="username" label-width="70px" label="用户名">
        <el-input v-model="editUserForm.username" disabled/>
      </el-form-item>
      <el-form-item prop="email" label-width="70px" label="邮箱">
        <el-input v-model="editUserForm.email"/>
      </el-form-item>
      <el-form-item prop="mobile" label-width="70px" label="手机">
        <el-input v-model="editUserForm.mobile"/>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
    <el-button @click="editdDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editUserBtn">确 定</el-button>
  </span>
  </el-dialog>
</div>
</template>

<script>
export default {
  name: 'Users',
  data () {
    // 验证邮箱的规则
    let checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        // 合法的邮箱
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }

    // 验证手机号的规则
    let checkMobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/

      if (regMobile.test(value)) {
        return cb()
      }

      cb(new Error('请输入合法的手机号'))
    }
    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      // 用户数据列表
      userList: [],
      // 总条数
      total: 0,
      // 添加用户对话框
      addUserdDialogVisible: false,
      // 添加用户表单数据
      addUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 验证规则
      addUserFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 修改用户对话框
      editdDialogVisible: false,
      // 修改用户表单信息
      editUserForm: {},
      // 验证规则
      editUserFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    // 获取用户列表
    async getUserList () {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 分页页码发生改变时
    handleSizeChange (newsize) {
      // console.log(newsize)
      this.queryInfo.pagesize = newsize
      this.getUserList()
    },
    handleCurrentChange (newpage) {
      this.queryInfo.pagenum = newpage
      this.getUserList()
    },
    // 更新用户状态信息
    async userStateChange (userInfo) {
      console.log(userInfo)
      const { data: res } = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
      // console.log(res)
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error('修改用户信息失败')
      }
      this.$message.success('更新用户状态成功')
    },
    // 添加用户
    addUser () {
      this.addUserdDialogVisible = true
    },
    // 关闭对话框清空表单数据
    addUserClosed () {
      this.$refs.addUserFormRef.resetFields()
    },
    // 点击确定按钮,添加用户
    addUserBtn () {
      this.$refs.addUserFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('users', this.addUserForm)
        // console.log(res)
        if (res.meta.status !== 201) return this.$message.error('添加用户失败')
        this.$message.success('添加用户成功')
        this.addUserdDialogVisible = false
        this.getUserList()
      })
    },
    // 修改用户对话框
    async editUser (id) {
      const { data: res } = await this.$http.get(`users/${id}`)
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error('查询用户信息失败')
      this.editUserForm = res.data
      this.editdDialogVisible = true
      // console.log(id)
    },
    // 关闭编辑对话框
    editDialogClosed () {
      this.$refs.editUserFormRef.resetFields()
    },
    // 点击确定按钮 完成编辑操作
    editUserBtn () {
      this.$refs.editUserFormRef.validate(async valid => {
        if (!valid) return this.$message.error('修改用户信息失败')
        const { data: res } = await this.$http.put(`users/${this.editUserForm.id}`, {
          email: this.editUserForm.email,
          mobile: this.editUserForm.mobile
        })
        // console.log(res)
        if (res.meta.status !== 200) return this.$message.error('修改用户信息失败')
        this.$message.success('修改用户信息成功')
        this.editdDialogVisible = false
        this.getUserList()
      })
    },
    // 点击删除按钮 完成删除操作
    async removeUserBtn (id) {
      let result = await this.$confirm('此操作将永久用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // console.log(result)
      if (result !== 'confirm') return this.$message.info('已经取消了删除')
      const { data: res } = await this.$http.delete(`users/${id}`)
      // console.log(res)
      if (res.meta.status !== 200) this.$message.error('删除用户失败')
      this.$message.success('删除用户成功')
      this.getUserList()
    }
  }
}
</script>

<style scoped>

</style>
